package OnTheBeachDB::Message;

use base qw/DBIx::Class/;
use DateTime;

# Load required DBIC stuff
__PACKAGE__->load_components(qw/Core/);

# Set the table name
__PACKAGE__->table('messages');

__PACKAGE__->resultset_class('OnTheBeachDB::ResultSet::Message');

# Set columns in table
__PACKAGE__->add_columns(
	qw/message_id parent_id forum_id created title name link message/);

# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/message_id/);

__PACKAGE__->belongs_to( forum => 'OnTheBeachDB::Forum', 'forum_id' );

## Thanks to rafl on #dbix-class! ##
## get the parent
__PACKAGE__->belongs_to(
	parent => __PACKAGE__,
	{ 'foreign.message_id' => 'self.parent_id' }
);
## get the children
__PACKAGE__->has_many(
	children => __PACKAGE__,
	{ 'foreign.parent_id' => 'self.message_id' }
);

=head1 NAME
    
    OnTheBeachDB::Message - A model object representing a forum message.
    
=head1 DESCRIPTION
  
=cut

1;

package OnTheBeachDB::ResultSet::Message;
use strict;
use warnings;
use base 'DBIx::Class::ResultSet';


## Count how many children this thread has
sub get_number_of_children {

	my ( $self, $id ) = @_;

	my $count = $self->search( { parent_id => $id } )->count();

	return $count;

}

## get all threads,
## including parents and their children
## and their children's children
## and their children's children's children...
sub get_thread_messages {

	my ( $self, $parent_id, $depth, $replies ) = @_;
	my @threads;

	## if no replies, return the given thread
	if ( !$replies ) {

		return $self->find($parent_id);

	}

	## Get the ids of any children
	my $rs =
	  $self->search( { parent_id => $parent_id }, { group_by => 'created', } );

	## Loop on each child found, if it has children,
	## recurse on this function, if now just generate it's link
	while ( my $id = $rs->next ) {

		## Let's see if this child message has children of it's own
		if ( $self->has_children( $id->message_id ) ) {

			push @threads,
			  $self->get_thread_messages( $id->message_id, $depth + 2 );

		}
		else {

			push @threads, $self->find( $id->message_id );

		}

	}

	return @threads;

}

# just get the replies
sub get_replies {
	my ( $self, $parent ) = @_;

	my @replies;

	@replies = $self->search(
		{ parent_id => $parent, },

	);

}

## See if this ID has any children
sub has_children {

	my ( $self, $id ) = @_;

	my $count = $self->search( { message_id => $id, } )->count();

	if ( $count > 0 ) {

		return 1;

	}
	else {

		return 0;

	}

}



1;
